package com.jemmyee.pizza.web.controller;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jemmyee.core.utils.EncryptUtils;
import com.jemmyee.core.web.controller.BaseController;
import com.jemmyee.pizza.entity.Dept;
import com.jemmyee.pizza.entity.Role;
import com.jemmyee.pizza.entity.User;
import com.jemmyee.pizza.service.IDeptService;
import com.jemmyee.pizza.service.IRoleService;
import com.jemmyee.pizza.service.IUserService;
import com.jemmyee.pizza.web.Constants;
import com.jemmyee.pizza.web.utils.CategoryXmlUtils;


/**
 * @Description:用户管理
 * @author:jemmyee@gmail.com
 * @date:2010-10-28
 * @version:v1.0
 */
@Controller
@RequestMapping("/admin/user")
public class UserController extends BaseController{
	
	private static Log log= LogFactory.getLog(UserController.class);
	
	@Autowired
	private IUserService<User> userService;
	@Autowired
	private IDeptService<Dept> deptService;
	@Autowired
	private IRoleService<Role> roleService;
	
	public String createTreeXml(HttpServletRequest request){
		List<Dept> depts=deptService.findAll();
		String filePath=getAppRoot(request)+Constants.CATEGORY_XML_FILE_PATH+File.separator+Constants.CATEGORY_XML_FILE_NAME;
	    CategoryXmlUtils.createXml(filePath, depts);
		return "ok";
	}
	
	@RequestMapping("/frame")
	public ModelAndView frame(HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		mv.setViewName("/admin/user/frame");
		return mv;
	}
	@RequestMapping("/tree")
	public ModelAndView tree(HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		mv.setViewName("/admin/user/tree");
		createTreeXml(request);
		return mv;
	}
	@RequestMapping("/right/{id}")
	public ModelAndView right(@PathVariable Integer id,HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		mv.addObject("items", userService.findByProperty("deptId",id));
		request.getSession().setAttribute("session_dept_user_id",id);
		mv.setViewName("/admin/user/right");
		return mv;
	}
	@RequestMapping("/welcome")
	public ModelAndView welcome(){
		ModelAndView mv=new ModelAndView();
		mv.setViewName("/admin/user/welcome");
		return mv;
	}
	
	@RequestMapping("/to_add")
	public ModelAndView toAdd(HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		mv.setViewName("/admin/user/add");
		Integer deptId=Integer.parseInt(request.getSession().getAttribute("session_dept_user_id").toString());
		mv.addObject("deptid", deptId);
		mv.addObject("roles",roleService.findAll());
		
		return mv;
	}

	@RequestMapping("/to_edit/{id}")
	public ModelAndView toEdit(@PathVariable Integer id,HttpServletRequest request){
		   ModelAndView mv=new ModelAndView();
		   mv.setViewName("/admin/user/edit");
		   mv.addObject("user",userService.findById(id));
		   Integer deptId=Integer.parseInt(request.getSession().getAttribute("session_dept_user_id").toString());
			mv.addObject("deptid", deptId);
			mv.addObject("roles",roleService.findAll());
		   return mv;
	}
	
	@RequestMapping("/to_add_role/{id}")
	public ModelAndView toAddRole(@PathVariable Integer id,HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		request.getSession().setAttribute("online_rid",id);
		Integer deptId=Integer.parseInt(request.getSession().getAttribute("session_dept_user_id").toString());
		mv.addObject("deptid", deptId);
		mv.addObject("roles", roleService.findAll());
		mv.setViewName("/admin/user/add_role");
		return mv;
	}
	
	@RequestMapping("/to_edit_role/{id}")
	public ModelAndView toEditRole(@PathVariable Integer id,HttpServletRequest request){
		ModelAndView mv=new ModelAndView();
		request.getSession().setAttribute("online_rid",id);
		
		Integer deptId=Integer.parseInt(request.getSession().getAttribute("session_dept_user_id").toString());
		mv.addObject("deptid", deptId);
		mv.addObject("roles", roleService.findAll());
		mv.addObject("user",userService.findById(id));
		mv.setViewName("/admin/user/add_role");
		return mv;
	}
	
	@RequestMapping("/add_role/{ids}")
	@ResponseBody
	public Map<String, Object> addRole(@PathVariable String ids,HttpServletRequest request)
	{   
		Map<String, Object> model = new HashMap<String, Object>();
		User user=userService.findById(Integer.parseInt(request.getSession().getAttribute("online_rid").toString()));
		user.setRoleIDS(ids);
		
		String names="";
		for(String id:ids.split("_"))
		{
			if(!id.equals(""))
			{
				Role role=roleService.findById(Integer.parseInt(id));
				names=names+role.getName()+" ";
			}
		
		}
		user.setRoleNames(names);
		
		userService.update(user);
		model.put("msg","succ");
		return model;
	}
	
	@RequestMapping("/add")
	@ResponseBody
	public Map<String, Object> add(@RequestBody User user,HttpServletRequest request)
	{   
		Map<String, Object> model = new HashMap<String, Object>();
		User temp=null;
		if(userService.findByProperty("name",user.getName())!=null&&userService.findByProperty("name",user.getName()).size()>0){
			temp=userService.findByProperty("name",user.getName()).get(0);
		}
		if(temp!=null&&temp.getName().equals(user.getName().trim()))
		{
			model.put("msg","error");
		}else
		{
			user.setSort(0);
			user.setStatus(Short.valueOf("0"));
			user.setCreateTime(new Date());
			user.setDeptId(Integer.parseInt(request.getSession().getAttribute("session_dept_user_id").toString()));
			user.setPassword(EncryptUtils.getMD5String(user.getPassword()));
//			String temps="";
//			String names="";
//			for(String id:ids.split("_"))
//			{
//				if(!id.equals(""))
//				{
//					temps=temps+id+"_";
//					Role role=roleService.findById(Integer.parseInt(id));
//					names=names+role.getName()+" ";
//				}
//			
//			}
			user.setRoleIDS("0");
//			user.setRoleNames(names);
			userService.save(user);
			model.put("msg","succ");
		}
		return model;
	}

	@RequestMapping("/edit")
	@ResponseBody
	public Map<String, Object> edit(@RequestBody User user,HttpServletRequest request)
	{   
		Map<String, Object> model = new HashMap<String, Object>();
		User temp=userService.findById(user.getId());
		if(!temp.getPassword().equals(EncryptUtils.getMD5String(user.getYuanPassword())))
		{
			model.put("msg","error");
		}else
		{
			temp.setName(user.getName());
			temp.setRealname(user.getRealname());
			temp.setRemark(user.getRemark());
			temp.setPassword(EncryptUtils.getMD5String(user.getPassword()));
//			temp.setRoleId(user.getRoleId());
			
//			String temps="";
//			String names="";
//			for(String id:ids.split("_"))
//			{
//				if(!id.equals(""))
//				{
//				temps=temps+id+"_";
//				Role role=roleService.findById(Integer.parseInt(id));
//				names=names+role.getName()+" ";
//				}
//			}
//			temp.setRoleIDS(temps);
//			temp.setRoleNames(names);
			
			userService.update(temp);
			model.put("msg","succ");
		}
		return model;
	}
	
	@RequestMapping(value="/delete/{id}")
	public String delete(@PathVariable Integer id,HttpServletRequest request){
	    userService.delete(userService.findById(id));
	    return "redirect:/admin/user/list/menu/0";
	}

}
